package com.dhh.sky.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import com.dhh.sky.R;
import com.dhh.sky.dao.DataBaseHelper;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;


public class ImageGridActivity extends Activity {
	private DataBaseHelper db;
	private String[] imgsNormal;
	private DisplayImageOptions options;
	private ImageLoader imageLoader = ImageLoader.getInstance();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.image_grid);
		imageLoader.init(ImageLoaderConfiguration.createDefault(this));
		imgsNormal = getIntent().getExtras().getStringArray("imgsNormal");
		db = new DataBaseHelper(getBaseContext());
        db.openDataBase();        
		options = new DisplayImageOptions.Builder()
			.showStubImage(R.drawable.stub_image)
			.showImageForEmptyUrl(R.drawable.image_for_empty_url)
			.cacheInMemory()
			.cacheOnDisc()
			.build();


		GridView gridView = (GridView) findViewById(R.id.gridview);
		gridView.setAdapter(new ImageAdapter());
		gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				startImageGalleryActivity(position);
			}
		});
	}	

	@Override
	protected void onStop() {
		imageLoader.stop();
		super.onStop();
	}
	
	private void startImageGalleryActivity(int position) {
		Intent intent = new Intent(this, ImagePagerActivity.class);
		intent.putExtra("imageUrls", imgsNormal);
		intent.putExtra("names", getIntent().getExtras().getStringArray("names"));
		intent.putExtra("ids", getIntent().getExtras().getStringArray("ids"));
		intent.putExtra("IMAGE_POSITION", position);
		startActivity(intent);
	}

	public class ImageAdapter extends BaseAdapter {
		@Override
		public int getCount() {
			return imgsNormal.length;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView imageView = (ImageView) convertView;
			if (imageView == null) {
				imageView = (ImageView) getLayoutInflater().inflate(R.layout.item_grid_image, parent, false);
			}

			imageLoader.displayImage(imgsNormal[position], imageView, options);

			return imageView;
		}
	}
}